#include "volumecenter.h"
#include "datacenter.h"

#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>
#include <QDebug>
#include <QSqlError>

VolumeCenter::VolumeCenter(const DataCenter &dataCenter):
		m_Database(dataCenter.getDatabase())
{
	createTable();
}

void VolumeCenter::createTable()
{
	QString createQuery("CREATE TABLE Volume("
						"ClientId int NOT NULL,"
						"StartTime nvarchar(100) NOT NULL,"
						"EndTime nvarchar(100) NOT NULL,"
						"Percentage int NOT NULL,"
						"FOREIGN KEY(ClientId) REFERENCES Client(Id) ON DELETE CASCADE)");
	QSqlQuery query;
	query.exec(createQuery);
}

std::vector<VolumeNode> VolumeCenter::query(int clientId)
{
	std::vector<VolumeNode> result;
	QString condition("SELECT * from Volume WHERE ClientId=%1");
	condition = condition.arg(QString::number(clientId));
	QSqlQuery query;
	if(!query.exec(condition))
	{
		qDebug()<<m_Database.lastError();
	}
	else
	{
		if(query.size() != -1)
			result.reserve(query.size());
		while(query.next())
		{
			VolumeNode volumeNode;
			QSqlRecord record = query.record();
			volumeNode.startTime = QTime::fromString(record.value("StartTime").toString(), "hh:mm");
			volumeNode.endTime = QTime::fromString(record.value("EndTime").toString(), "hh:mm");
			volumeNode.percentage = record.value("Percentage").toInt();
			result.push_back(volumeNode);
		}
	}
	return result;

}

void VolumeCenter::newVolumePlan(int clientId, const std::vector<VolumeNode> &volumePlan)
{
	QSqlQuery query;
	QString deleteOri("DELETE FROM Volume WHERE ClientId=%1");
	deleteOri = deleteOri.arg(QString::number(clientId));
	if(!query.exec(deleteOri))
	{
		qDebug()<<m_Database.lastError();
	}

	for(size_t i = 0; i < volumePlan.size(); ++i)
	{
		const VolumeNode& volumeNode = volumePlan[i];
		QString newNodeQuery = "INSERT INTO Volume VALUES(%1,'%2','%3',%4)";
		newNodeQuery = newNodeQuery.arg(QString::number(clientId),
						 volumeNode.startTime.toString("hh:mm"),
						 volumeNode.endTime.toString("hh:mm"),
						 QString::number(volumeNode.percentage) );
		if(!query.exec(newNodeQuery))
		{
			qDebug()<<m_Database.lastError();
		}
	}
}
